# -*- coding: utf-8 -*-
import sys
import ast
import json
import requests
import re

import console
import clipboard
import webbrowser

# 请求头部
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4083.0 Safari/537.36",
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7",
    "Upgrade-Insecure-Requests": "1"
}

'''
    封装提示
'''
def alert(text):
    console.alert(text, '', '确定', hide_cancel_button=True)

'''
    获取ios捷近传递的参数
'''


def get_url():
    rawInput = sys.argv.__str__()
    listInput = ast.literal_eval(rawInput)

    # 判断ins地址，并获取
    ins_url = get_ins_url(listInput)
    if len(ins_url) > 0:
        return ins_url


'''
    从参数中获取地址
'''


def get_ins_url(input):
    if len(input) == 2:
        if 'https://www.instagram.com/' in str(input[1]):
            return input[1]
    else:
        alert('ins链接无效')
        exit(1)


'''
    访问ins网页，获取资源链接
'''


def crawl(u):
    try:
        res = requests.get(u, headers=headers)
        patten = '(?<=window\\._sharedData = ).*(?=;<\\/script>)'
        result = re.search(patten, res.content.decode('utf-8'), flags=0)

        json_data = json.loads(result.group())

        shortcode_media = json_data['entry_data']['PostPage'][0]['graphql']['shortcode_media']

        result_urls = []

        # 是否为视频
        if shortcode_media['is_video']:
            result_urls(shortcode_media['video_url'])
        else:
            edges_ = shortcode_media['edge_sidecar_to_children']['edges']
            for edg in edges_:
                node_ = edg['node']
                if node_['is_video']:
                    result_urls.append(node_['video_url'])
                else:
                    resources_ = node_['display_resources']
                    # 取display_resources数组最大像素的图片
                    result_urls.append(resources_[len(resources_) - 1]['src'])
        print(result_urls)

        return None if len(result_urls) == 0 else result_urls
    except:
        alert('路径解析失败')


'''
    入口函数
'''
if __name__ == '__main__':
    url = get_url()
    if len(url) > 0:
        urls = crawl(url)
        if len(urls) > 0:
            clipboard.set(urls)  # 将链接添加到剪贴板
            webbrowser.open('workflow://')  # 返回 Workflow 应用
        else:
            alert('路径解析失败')
    else:
        alert('ins链接有误')
